do (angular) ->

  tini = angular.module 'tini'

  .controller 'home', ($scope, $routeParams, $timeout, $anchorScroll, index, title) ->
    markAsArchive $scope
    title()

    index (data) ->
      procArchivePosts $scope, $routeParams, data.posts
      scrollToAnchor $timeout, $anchorScroll

  .controller 'post', ($scope, $location, $timeout, $anchorScroll, index, title) ->
    id = $location.path().substr 1
    index (data) ->
      post = data.indexes[id]
      if post
        $scope.post = post
        title post.title
        scrollToAnchor $timeout, $anchorScroll
      else
        $location.path '/'

  angular.forEach
    category: 'categories'
    tag: 'tags'
    archive: 'archives'
  , (indexName, type) ->
      tini.controller type, [
        '$scope'
        '$location'
        '$routeParams'
        '$timeout'
        '$anchorScroll'
        'index'
        'title'
        ($scope, $location, $routeParams, $timeout, $anchorScroll, index, title) ->
          name = $routeParams[type]
          markAsArchive $scope
          title name

          index (data) ->
            if data[indexName][name]
              procArchivePosts $scope, $routeParams, data[indexName][name]
              scrollToAnchor $timeout, $anchorScroll
            else
              $location.path '/'
      ]

  # 获取当前页码
  getPage = ($scope, $routeParams) ->
    page = parseInt $routeParams.page
    $scope.page = page || 1

  # 根据页码获取当前页的文章列表
  getPosts = ($scope, src, page) ->
    postPerPage = $scope.config.postPerPage
    start = postPerPage * (page - 1)
    start = if start < src.length || start > -1 then start else 0
    end = start + postPerPage
    end = if end < src.length then end else src.length
    $scope.posts = src.slice start, end

  # 分页列表
  getPagination = ($scope, src, page) ->
    postPerPage = $scope.config.postPerPage
    max = Math.ceil src.length / postPerPage
    $scope.pagination = [1..max]

    path = $scope.global.path
    pathPageIndex = path.indexOf '/page/'
    path = path.substr(0, pathPageIndex) if pathPageIndex > -1
    path = '' if path == '/'
    $scope.base = path

  # 处理存档页
  procArchivePosts = ($scope, $routeParams, src) ->
    page = getPage $scope, $routeParams
    getPosts $scope, src, page
    getPagination $scope, src, page

  markAsArchive = ($scope) ->
    $scope.archive = true

  # 控制滚动条
  scrollToAnchor = ($timeout, $anchorScroll) ->
    $timeout ->
      $anchorScroll()
    , 300
